import { Box } from "@mui/system";
import { Mask, MaskProps, Swiper } from "antd-mobile";
import React, { lazy, PropsWithChildren, Suspense, useEffect, useMemo, useRef } from "react";
import { FileViewer_Mime } from "../../const";

import mime from "mime";
import { UploadFile } from "antd";

export interface ViewerCommonProps {
  src?: string; //资源地址
  onClose?: () => void; //关闭预览
  fileInfo?: string | UploadFile<any>; //文件的原信息
}
export interface FileViewerProps extends PropsWithChildren, MaskProps {
  fileList?: (UploadFile<any> | string)[]; //预览的文件列表
  defaultIndex?: number;
  visible?: boolean;
  onClose?: () => void;
}
const FileViewer = ({ fileList, defaultIndex, visible, onClose, children, style, ...otr }: FileViewerProps) => {
  return (
    <>
      <Mask visible={visible} style={{}} {...otr}>
        {visible ? (
          <Swiper defaultIndex={defaultIndex}>
            {fileList?.map((file, index) => {
              const fileName = typeof file == "object" ? file?.name : file;
              const srcPath =
                //转换成BlobUrl
                file instanceof Object ? file.originFileObj && URL.createObjectURL(file.originFileObj) : file;
              return (
                <Swiper.Item key={index}>
                  <Suspense key={index} fallback={null}>
                    {React.createElement(
                      lazy(
                        () =>
                          FileViewer_Mime[mime.getType(fileName.split(".")?.slice(-1)?.[0] || "image/png")?.split("/")?.[0] as keyof typeof FileViewer_Mime] ||
                          FileViewer_Mime[mime.getType("image/png")?.split("/")?.[0] as keyof typeof FileViewer_Mime]
                      ),
                      {
                        src: srcPath,
                        visible: visible,
                        onClose,
                        fileInfo: file,
                      }
                    )}
                  </Suspense>
                </Swiper.Item>
              );
            })}
          </Swiper>
        ) : null}
      </Mask>
    </>
  );
};

export default FileViewer;
